import sys
from numpy import *
from matplotlib import pyplot, cm
import scipy.io, scipy.misc, scipy.signal
import copy

def gabor( size, sigma, theta, lambd, gamma, psi=0.5*pi, separate=False ):
    xmax, ymax = size / 2, size / 2
    x, y = meshgrid( linspace(-xmax, xmax, size ), linspace(-ymax, ymax, size ) )
    x_theta = x * cos(theta) + y * sin(theta)
    y_theta = -x * sin(theta) + y * cos(theta)
    gauss = exp( - ( x_theta**2 + gamma**2 * y_theta **2 ) / (2. * sigma**2) )
    grating = cos( (2 * pi / lambd) * x_theta + psi )
    # if you want to have the gaussian and sinusoidal components separated
    if separate:
        return (-gauss, grating)
    else:
        return -gauss * grating

def get_fetures_from_image(image=''):
    img = scipy.misc.imread(image)
    rows, cols = shape( img )[0], shape(img)[1]
    img = scipy.misc.imresize(img, (rows/2, cols/2))
#    grayscale = img.dot([0.299, 0.587, 0.144])
    grayscale = img
    rows, cols = shape( grayscale )
    
    theta = 0.0 * pi / 180.0
    lambd = 1.0 / 0.04
    size = 20 # size of kernel
    sigma = 1.0 # the standard deviation of Gaussian, the higher the stdev, the less sensitive the filter is
    gamma = 1. # basically controls gamma for y's sigma
    psi = 0.5 * pi # phase shift
    
    data = [0] * 18
    vect_data = [copy.deepcopy(data)] * cols
    mat_data = [copy.deepcopy(vect_data)] * rows

    
    count = 0
    for theta_iter in [0, 30, 60, 90, 120, 150]:
        for freq in [0.3, 0.6, 0.9]:
            lambd = 1. / freq # lambda is wavelength
            theta = theta_iter * pi / 180. # theta is orientation
            # create the kernel
            kernel = gabor( size=size, sigma=sigma, theta=theta, lambd=lambd, gamma=gamma, psi=psi )
            convolved = scipy.signal.convolve2d(grayscale, kernel, mode='same' )

            for i in range(rows):
                for j in range(cols):
                    mat_data[i][j][count] = convolved[i][j]
            count += 1
    fetures = []
    for count in range(18):
        for i in range(rows):
            for j in range(cols):
                fetures.append(mat_data[i][j][count])
    del data
    del vect_data
    del mat_data
    #return array(fetures)
    return fetures

#print get_fetures_from_image('data/train/faces_01_01.png')
#get_fetures_from_image('data/faces_01_02.png')
#get_fetures_from_image('data/faces_02_01.png')
